// Refresh data function
function refreshinfo() {
    var xhr = new XMLHttpRequest();
    var url = "";
    xhr.open("POST", url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.responseText);
            var val = xhr.responseText.split(" ");
            updateDataDisplays(val);
        }
    };
    xhr.send("get");

    // Animate refresh button
    const refreshButton = document.querySelector('.refresh-button');
    refreshButton.style.transform = 'rotate(360deg)';
    setTimeout(() => {
        refreshButton.style.transform = 'rotate(0deg)';
    }, 300);
}

// Function to update data-display elements
function updateDataDisplays(val) {
    const displays = document.querySelectorAll('.data-display');
    const units = [' °C', ' %', ' lux', ' °C', ' %', ' ppm', ' ppm', ' %'];
    
    if (val[0]) {  
        displays[0].textContent = val[0] + units[0];  // 环境温度
    }  
    if (val[1]) {  
        displays[1].textContent = val[1] + units[1];  // 环境湿度
    }  
    if (val[3]) {  
        displays[2].textContent = val[3] + units[2];  // 光照强度
    }  
    // Commented out as per the original code
    if (val[7]) {  
        displays[3].textContent = val[7] + units[3];  // 棚内温度
    }  
    if (val[6]) {  
        displays[4].textContent = val[6] + units[4];  // 棚内湿度
    }  
    if (val[2]) {  
        displays[5].textContent = val[2] + units[5];  // 二氧化碳
    }  
    if (val[5]) {  
        displays[6].textContent = val[5] + units[6];  // 氧气
    }  
    if (val[4]) {  
        displays[7].textContent = val[4] + units[7];  // 土壤湿度
    }  
}

// Initial data load
document.addEventListener('DOMContentLoaded', refreshinfo);

// Control switch event listeners
const controls = [
    { id: 'chu', key: 303, type: 222 },
    { id: 'wet', key: 304, type: 222 },
    { id: 'lig', key: 305, type: 222 },
    { id: 'buz', key: 307, type: 222 },
    { id: 'pup', key: 306, type: 222 }
];

controls.forEach(control => {
    const checkbox = document.getElementById(control.id);
    checkbox.addEventListener('change', function() {
        var xhr = new XMLHttpRequest();
        var url = "";
        var post_req = {
            type: 2,
            msgtype: control.msgtype,
            key: control.key,
            val: this.checked ? "1" : "0"
        };
        
        xhr.open("POST", url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    console.log("Request successful");
                } else {
                    console.log("Request failed with status:", xhr.status);
                }
            }
        };
        xhr.send(JSON.stringify(post_req));
    });
});

// Auto refresh every 30 seconds
setInterval(refreshinfo, 30000);